#include"TopK.h"

void adjust_down_(int * arr, int  size)
{
   	for (int i = (size - 1 - 1) / 2; i >= 0; i--)
	{
		int father = i;
		int  child = father * 2 + 1;
		while (child < size)
		{
			if (child + 1 < size && arr[child] > arr[child + 1])
			{
				child++;
			}
			if (arr[father] > arr[child])
			{
				int  mid = arr[father];
				arr[father] = arr[child];
				arr[child] = mid;

				father = child;
				child = father * 2 + 1;
			}
			else break;
		}
	}
}

void adjust_down(int* arr, int  size)
{
	assert(arr);
	int father = 0;
	int  child = 1;
	while (child < size)
	{
		if (child + 1 < size && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[father] > arr[child])
		{
			int mid = arr[father];
			arr[father] = arr[child];
			arr[child] = mid;

			father = child;
            child = father * 2 + 1;
		}
		else break;
	}
}

void file_create()
{
	int n = 10000;
	srand(time(0));

	const char* file = "data.txt";
	FILE* f = fopen(file, "w");
	if (f == NULL)
	{
		perror("fopen fail");
		exit(1);
	}
	for (int i = 1; i <= n; i++)
	{
		int  x = rand() % 100000 ;
		fprintf(f, "%d\n",x);
	}
	fclose(f);

}

void TopK()
{
	int k; scanf("%d", &k);

	const char* file = "data.txt";
	FILE* f = fopen(file, "r");
	if (f == NULL)
	{
		perror("fopen fail");
		exit(1);
	}

	int* arr = (int*)malloc(k * sizeof(int));
	if (arr == NULL)
	{
		perror("malloc fail");
		exit(2);
	}

	for (int i = 0; i < k; i++)
	{
		fscanf(f, "%d", &arr[i]);
	}

	adjust_down_(arr,k);

	int x = 0;
	while (fscanf(f, "%d", &x) != EOF)
	{
		if (x > arr[0])
		{
			arr[0] = x;
			adjust_down(arr, k);
		}
	}
	for ( long i = 0; i < k; i++)
		printf("%d ", arr[i]);
	printf("\n");

	fclose(f);
	free(arr);
	arr = NULL;
}